<template>
  <div class="container">
    <el-form ref="form" :model="formData" :rules="formRules" label-width="100px">
      <el-form-item>
        <el-avatar v-if="formData.avatar" :size="100" :src="formData.avatar" fit="cover"></el-avatar>
        <el-upload
          v-else
          class="avatar-uploader"
          action="/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="账号" prop="id">
        <el-input v-model="formData.id"></el-input>
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="formData.sex">
          <el-radio label="0">男</el-radio>
          <el-radio label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="电话" prop="phone">
        <el-input v-model="formData.phone"></el-input>
      </el-form-item>

      <el-form-item label="学校" prop="school">
        <el-select v-model="formData.school" filterable @change="handleSchoolChange">
          <el-option
            v-for="item in schools"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue';
import { useStore } from 'vuex';
import { toast } from "~/composables/util";
// 引入本地头像（使用 ESM 语法替代 require）
import avatarImg from '/src/assets/imgs/a.jpg';

const store = useStore();
const form = ref(null);

// 从 Vuex 获取用户信息并初始化表单
const formData = ref({
  avatar: avatarImg, // 使用导入的头像
  id: '',
  name: '高玉秀',
  sex: '0',
  phone: '15386819574',
  school: ''
});

// 表单验证规则
const formRules = ref({
  phone: [
    { pattern: /^\d{11}$/, message: '电话号码格式不正确', trigger: 'blur' }
  ]
});

// 学校列表
const schools = [
  { id: 1, name: '太原工业学院' },
  { id: 2, name: '中北大学' },
  { id: 3, name: '清华大学' }
];

// 头像上传成功处理
const handleAvatarSuccess = (response, file, fileList) => {
  formData.value.avatar = response.url; // 更新头像
};

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    toast('上传头像图片只能是 JPG 格式!', 'error');
  }
  if (!isLt2M) {
    toast('上传头像图片大小不能超过 2MB!', 'error');
  }
  return isJPG && isLt2M;
};

// 学校选择变化处理
const handleSchoolChange = (value) => {
  // 可选：验证学校是否存在
  const exists = schools.some(school => school.name === value);
  if (!exists) {
    toast('所选学校不存在，请重新选择', 'warning');
  }
};

// 表单提交处理  13.讲解
const handleSubmit = () => {
  form.value.validate(async (valid) => {
    if (valid) {
      const updatedInfo = {
        ...formData.value
      };
      
      await store.dispatch('updateinfo', updatedInfo);
      toast('更新成功', 'success');
      console.log('更新后的用户信息:', store.state.user);
      
      // 重新加载用户信息
      await store.dispatch('getinfo');
      formData.value = {
        ...store.state.user,
        // 保持固定显示的姓名和电话
        name: '高玉秀',
        phone: '15386819574'
      };
    }
  });
};
// 6.讲解
// 组件挂载前获取用户信息
onBeforeMount(async () => {
  await store.dispatch('getinfo');
  
  // 初始化表单数据，保留固定显示的姓名和电话
  formData.value = {
    ...store.state.user,
    avatar: avatarImg,
    name: '高玉秀',
    phone: '15386819574'
  };
});
</script>

<style src="~/assets/css/userinfo.css" scoped></style>